//
//  HeartVideoLayout.m
//  miaopai
//
//  Created by duyifang on 15/11/24.
//  Copyright © 2015年 Crow Zhang. All rights reserved.
//

#import "HeartVideoLayout.h"

#define kWidth [UIScreen mainScreen].bounds.size.width
@implementation HeartVideoLayout
//重写系统的prepareLayout方法，准备布局item之前会被调用
-(void)prepareLayout
{
    //调用父类的方法
    [super prepareLayout];
    
    self.maxHeight = 0;
    
    //用来存放item属性
    self.array = [NSMutableArray array];
    
    //第一列item y坐标的初始值
    CGFloat leftY = 0;
    
    //第二列item y坐标的初始值
    CGFloat rightY = 0;
    
    
    //计算contentView
    //第一步
    CGFloat maxLeft = 0;
    CGFloat maxRight = 0;
    
    //计算当前分区有多少个item
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    
    //设置每个item的属性
    for (int i = 0; i < count; i++) {
        
        //生成item的下标
        NSIndexPath *index = [NSIndexPath indexPathForItem:i inSection:0];

        UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:index];
        
        //默认X坐标为0
        float offSetX = 0;
        
        if (i % 2 == 0) {
            //设置第一列item X坐标
            offSetX = 10;
        }else {
            offSetX = 20 + (kWidth - 30) / 2;
        }
        
        //获取协议返回的size
        CGSize itemSize = [self.delegate collectionview:self.collectionView layout:self sizeForItemAtItemIndexPath:index];
        //设置每一个item的属性
        if (i % 2 == 0) {
            //设置第一列item
            attributes.frame = CGRectMake(offSetX, leftY, itemSize.width, itemSize.height);
            //记录左侧所有item高度
            maxLeft = leftY + itemSize.height;
            leftY += itemSize.height + 10;
            
        }else {
            attributes.frame = CGRectMake(offSetX, rightY, itemSize.width, itemSize.height);
            maxRight = rightY + itemSize.height;
            rightY += itemSize.height + 10;
        }
        
        self.maxHeight = maxLeft > maxRight ? maxLeft + 10 : maxRight + 10;
        
        //存入数组中
        [self.array addObject:attributes];
        
    }
    
    
}

//重写系统方法，初始的layout的外观由该方法返回的UICollectionViewLayoutAttributes来决定
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < [self.array count]; i++) {
        UICollectionViewLayoutAttributes *att = [self.array objectAtIndex:i];
        //判断第二个rect是不是在第一个rect范围之内
        if (CGRectIntersectsRect(rect, att.frame)) {
            
            [arr addObject:att];
        }
        
    }
    return arr;
}

//重新设置滑动范围contentSize
-(CGSize)collectionViewContentSize
{
    return CGSizeMake(self.collectionView.frame.size.width, self.maxHeight);
}

@end
